<template>
  <div class="defer-exam-system">
    <!-- 管理员视图（模拟） -->
      <div class="filter-container">
        <a-select
          v-model="filterStatus"
          style="width: 150px"
          placeholder="按状态筛选"
          @change="handleFilterChange"
        >
          <a-select-option value="all">全部状态</a-select-option>
          <a-select-option value="pending">待审核</a-select-option>
          <a-select-option value="approved">已批准</a-select-option>
          <a-select-option value="rejected">已拒绝</a-select-option>
        </a-select>
        <a-input-search
          v-model="searchKeyword"
          placeholder="搜索学生姓名/学号"
          style="width: 250px; margin-left: 10px"
          @search="handleSearch"
        />
      </div>
      
      <a-table
        :columns="adminColumns"
        :dataSource="filteredApplications"
        rowKey="applyId"
        :pagination="{pageSize: 5}"
      >
        <template slot="status" slot-scope="text, record">
          <a-select
            v-if="editableStatusId === record.applyId"
            :value="record.status"
            style="width: 100px"
            @change="(value) => handleStatusChange(record, value)"
          >
            <a-select-option value="pending">待审核</a-select-option>
            <a-select-option value="approved">已批准</a-select-option>
            <a-select-option value="rejected">已拒绝</a-select-option>
          </a-select>
          <a-tag v-else :color="statusColorMap[record.status]">
            {{ statusTextMap[record.status] }}
          </a-tag>
        </template>
        <template slot="action" slot-scope="text, record">
          <a @click="editStatus(record)">{{ editableStatusId === record.applyId ? '保存' : '修改状态' }}</a>
          <a-divider type="vertical" />
          <a @click="viewAdminApplicationDetail(record)">详情</a>
        </template>
      </a-table>

    <!-- 申请详情模态框 -->
    <a-modal
      :title="`缓考申请详情 - ${currentApplication.studentName || ''}`"
      :visible="detailVisible"
      @cancel="detailVisible = false"
      :footer="null"
      width="700px"
    >
      <a-descriptions bordered :column="1">
        <a-descriptions-item label="申请ID">{{ currentApplication.applyId }}</a-descriptions-item>
        <a-descriptions-item label="学生信息">
          {{ currentApplication.studentName }} ({{ currentApplication.studentId }})
        </a-descriptions-item>
        <a-descriptions-item label="申请课程">
          <div v-for="course in currentApplication.courses" :key="course.courseId">
            {{ course.courseName }} - {{ course.examTime }} ({{ course.examLocation }})
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="申请时间">{{ currentApplication.applyTime }}</a-descriptions-item>
        <a-descriptions-item label="当前状态">
          <a-tag :color="statusColorMap[currentApplication.status]">
            {{ statusTextMap[currentApplication.status] }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="申请原因">{{ currentApplication.reason }}</a-descriptions-item>
        <a-descriptions-item label="证明材料">
          <div v-for="file in currentApplication.attachments" :key="file.name">
            <a-icon type="paper-clip" /> {{ file.name }}
          </div>
          <span v-if="currentApplication.attachments.length === 0">无</span>
        </a-descriptions-item>
        <a-descriptions-item label="审核意见" v-if="currentApplication.status !== 'pending'">
          {{ currentApplication.reviewComment || '无' }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script>
export default {
  beforeCreate() {
    this.applyForm = this.$form.createForm(this);
  },
  
  data() {
    return {
      currentStep: 0,
      selectedCourseKeys: [],
      fileList: [],
      submitting: false,
      detailVisible: false,
      currentApplication: {
		  courses:[],
		  applyId:'',
		  applyTime:'',
		  attachments:[],
		  reason:'',
	  },
      editableStatusId: null,
      filterStatus: 'all',
      searchKeyword: '',
      
      // 状态映射
      statusTextMap: {
        pending: '待审核',
        approved: '已批准',
        rejected: '已拒绝',
        canceled: '已撤销'
      },
      statusColorMap: {
        pending: 'orange',
        approved: 'green',
        rejected: 'red',
        canceled: 'gray'
      },
      
      // 可申请课程数据
      availableCourses: [
        {
          courseId: 'C001',
          courseName: '高等数学（上）	',
          credit: 4,
          teacher: '李红梅',
          examTime: '2024-09-10 08:30-10:30',
          examLocation: '1号教学楼201',
          seatNumber: 'A201-15'
        },
        {
          courseId: 'C002',
          courseName: 'PLC与工业控制技术',
          credit: 3,
          teacher: '李娜',
          examTime: '2024-09-11 14:00-16:00',
          examLocation: '2号教学楼105',
          seatNumber: 'B105-08'
        },
        {
          courseId: 'C003',
          courseName: '计算机基础',
          credit: 2,
          teacher: '王雪',
          examTime: '2024-09-12 09:00-11:00',
          examLocation: '实验楼302',
          seatNumber: 'LAB302-12'
        }
      ],
      
      // 我的申请记录
      myApplications: [
        {
          applyId: 'A2023001',
          studentId: '20231001',
          studentName: '刘洋',
          applyTime: '2024-09-01 10:30',
          courses: [
            {
              courseId: 'C001',
              courseName: '高等数学（上）	',
              examTime: '2024-09-10 08:30-10:30'
            }
          ],
          reason: '因病住院治疗，无法参加考试',
          attachments: [{ name: '医院证明.pdf' }],
          status: 'approved',
          reviewComment: '证明材料充分，批准缓考'
        },
        {
          applyId: 'A2023002',
          studentId: '20231001',
          studentName: '刘洋',
          applyTime: '2024-09-05 14:20',
          courses: [
            {
              courseId: 'C002',
              courseName: 'PLC与工业控制技术',
              examTime: '2024-09-11 14:00-16:00'
            }
          ],
          reason: '参加国际学术会议',
          attachments: [{ name: '会议邀请函.jpg' }, { name: '审批表.pdf' }],
          status: 'pending'
        }
      ],
      
      // 所有申请记录（管理员视图）
      allApplications: [
        {
          applyId: 'A2023001',
          studentId: '20231001',
          studentName: '刘洋',
          applyTime: '2024-09-01 10:30',
          courses: [
            {
              courseId: 'C001',
              courseName: '高等数学（上）	',
              examTime: '2024-09-10 08:30-10:30',
              seatNumber: 'A201-15'
            }
          ],
          reason: '因病住院治疗，无法参加考试',
          attachments: [{ name: '医院证明.pdf' }],
          status: 'approved',
          reviewComment: '证明材料充分，批准缓考'
        },
        {
          applyId: 'A2023002',
          studentId: '20231001',
          studentName: '刘洋',
          applyTime: '2024-09-05 14:20',
          courses: [
            {
              courseId: 'C002',
              courseName: 'PLC与工业控制技术',
              examTime: '2024-09-11 14:00-16:00',
              seatNumber: 'B105-08'
            }
          ],
          reason: '参加国际学术会议',
          attachments: [{ name: '会议邀请函.jpg' }, { name: '审批表.pdf' }],
          status: 'pending'
        },
        {
          applyId: 'A2023003',
          studentId: '20231002',
          studentName: '赵宇',
          applyTime: '2024-09-02 09:15',
          courses: [
            {
              courseId: 'C003',
              courseName: '计算机基础',
              examTime: '2024-09-12 09:00-11:00',
              seatNumber: 'LAB302-12'
            }
          ],
          reason: '家庭突发情况需回家处理',
          attachments: [{ name: '情况说明.docx' }],
          status: 'rejected',
          reviewComment: '理由不充分，请按时参加考试'
        },
        {
          applyId: 'A2023004',
          studentId: '20231003',
          studentName: '周婷',
          applyTime: '2024-09-03 16:40',
          courses: [
            {
              courseId: 'C001',
              courseName: '高等数学（上）	',
              examTime: '2024-09-10 08:30-10:30',
              seatNumber: 'A201-22'
            },
            {
              courseId: 'C003',
              courseName: '计算机基础',
              examTime: '2024-09-12 09:00-11:00',
              seatNumber: 'LAB302-05'
            }
          ],
          reason: '代表学校参加省级体育比赛',
          attachments: [{ name: '参赛通知.pdf' }, { name: '教练证明.jpg' }],
          status: 'approved',
          reviewComment: '代表学校参赛，批准缓考'
        }
      ],
      
      // 表格列定义
      courseColumns: [
        { title: '课程名称', dataIndex: 'courseName' },
        { title: '学分', dataIndex: 'credit' },
        { title: '任课教师', dataIndex: 'teacher' },
        { title: '考试信息', scopedSlots: { customRender: 'examInfo' } },
        { title: '座位号', dataIndex: 'seatNumber' }
      ],
      
      applyRecordColumns: [
        { title: '申请ID', dataIndex: 'applyId' },
        { title: '申请课程', customRender: (text, record) => record.courses.map(c => c.courseName).join(', ') },
        { title: '申请时间', dataIndex: 'applyTime' },
        { title: '状态', scopedSlots: { customRender: 'status' } },
        { title: '操作', scopedSlots: { customRender: 'action' } }
      ],
      
      adminColumns: [
        { title: '申请ID', dataIndex: 'applyId' },
        { title: '学生姓名', dataIndex: 'studentName' },
        { title: '学号', dataIndex: 'studentId' },
        { title: '申请课程', customRender: (text, record) => record.courses.map(c => c.courseName).join(', ') },
        { title: '申请时间', dataIndex: 'applyTime' },
        { title: '状态', scopedSlots: { customRender: 'status' } },
        { title: '操作', scopedSlots: { customRender: 'action' } }
      ]
    };
  },
  
  computed: {
    selectedCourses() {
      return this.availableCourses.filter(course => 
        this.selectedCourseKeys.includes(course.courseId)
      );
    },
    
    filteredApplications() {
      let apps = [...this.allApplications];
      
      // 状态筛选
      if (this.filterStatus !== 'all') {
        apps = apps.filter(app => app.status === this.filterStatus);
      }
      
      // 关键词搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        apps = apps.filter(app => 
          app.studentName.toLowerCase().includes(keyword) || 
          app.studentId.toLowerCase().includes(keyword)
        );
      }
      
      return apps;
    }
  },
  
  methods: {
    // 步骤切换
    nextStep() {
      this.currentStep++;
    },
    
    prevStep() {
      this.currentStep--;
    },
    
    // 课程选择
    onSelectChange(selectedRowKeys) {
      this.selectedCourseKeys = selectedRowKeys;
    },
    
    // 文件上传
    beforeUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('文件大小不能超过5MB');
      }
      return isLt5M;
    },
    
    handleUploadChange(info) {
      let fileList = [...info.fileList];
      fileList = fileList.slice(-3); // 最多上传3个文件
      this.fileList = fileList;
    },
    
    // 提交申请
    handleSubmit() {
      this.applyForm.validateFields((err, values) => {
        if (!err) {
          this.submitting = true;
          
          // 模拟提交延迟
          setTimeout(() => {
            const newApplication = {
              applyId: `A${new Date().getTime()}`,
              studentId: '20231001',
              studentName: '刘洋',
              applyTime: new Date().toLocaleString(),
              courses: this.selectedCourses.map(c => ({
                courseId: c.courseId,
                courseName: c.courseName,
                examTime: c.examTime
              })),
              reason: values.reason,
              attachments: this.fileList,
              status: 'pending'
            };
            
            this.myApplications.unshift(newApplication);
            this.allApplications.unshift(newApplication);
            
            this.$message.success('缓考申请提交成功');
            this.submitting = false;
            this.currentStep = 0;
            this.selectedCourseKeys = [];
            this.fileList = [];
            this.applyForm.resetFields();
          }, 1000);
        }
      });
    },
    
    // 查看申请详情
    viewApplicationDetail(record) {
      this.currentApplication = record;
      this.detailVisible = true;
    },
    
    // 撤销申请
    cancelApplication(record) {
      this.$confirm({
        title: '确认撤销申请?',
        content: '撤销后如需缓考需要重新申请',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          const index = this.myApplications.findIndex(app => app.applyId === record.applyId);
          if (index !== -1) {
            this.myApplications[index].status = 'canceled';
          }
          
          const adminIndex = this.allApplications.findIndex(app => app.applyId === record.applyId);
          if (adminIndex !== -1) {
            this.allApplications[adminIndex].status = 'canceled';
          }
          
          this.$message.success('申请已撤销');
        }
      });
    },
    
    // 管理员操作
    viewAdminApplicationDetail(record) {
      this.currentApplication = record;
      this.detailVisible = true;
    },
    
    editStatus(record) {
      if (this.editableStatusId === record.applyId) {
        // 保存修改
        const index = this.allApplications.findIndex(app => app.applyId === record.applyId);
        if (index !== -1) {
          this.allApplications[index].status = record.status;
          
          // 同步更新到我的申请记录（如果是当前学生的申请）
          const myIndex = this.myApplications.findIndex(app => app.applyId === record.applyId);
          if (myIndex !== -1) {
            this.myApplications[myIndex].status = record.status;
          }
        }
        this.editableStatusId = null;
        this.$message.success('状态更新成功');
      } else {
        // 开始编辑
        this.editableStatusId = record.applyId;
      }
    },
    
    handleStatusChange(record, value) {
      record.status = value;
    },
    
    handleFilterChange(value) {
      this.filterStatus = value;
    },
    
    handleSearch(value) {
      this.searchKeyword = value;
    }
  }
};
</script>

<style scoped>
.defer-exam-system {
  padding: 20px;
}

.mb-20 {
  margin-bottom: 20px;
}

.steps-action {
  margin-top: 20px;
  text-align: center;
}

.confirm-info {
  margin-bottom: 20px;
}

.upload-tip {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}

.filter-container {
  margin-bottom: 20px;
}
</style>